package com.dmall.opening.up.records;

import com.dmall.opening.up.core.Criteria;
import com.dmall.opening.up.core.Order;
import com.dmall.opening.up.core.Page;
import com.dmall.opening.up.core.Request;
import com.dmall.opening.up.records.dao.mysql.mybatis.mapper.OrderMapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

@Component
public class OrderRepository implements com.dmall.opening.up.core.OrderRepository {

    @Resource
    private OrderMapper mapper;

    @Override
    public Order create(Request<String, Object> request) {
        mapper.insert(request);
        mapper.insertItems(request);
        return findOne(request.longValue("id")).orElseThrow(RuntimeException::new);
    }

    @Override
    public Optional<Order> findOne(Long id) {
        final Order order = mapper.findById(id);
        if (order == null) {
            return Optional.empty();
        }
        OrderRecord record = ((OrderRecord) order);
        record.items.forEach(item -> item.order = record);
        return Optional.of(record);
    }

    @Override
    public Page<Order> paging(Criteria criteria) {
        final Long page = criteria.page();
        final Long pageSize = criteria.pageSize();
        final long begin = (page - 1) * pageSize;
        final long count = mapper.countByCriteria(criteria);
        final List<Order> entries = mapper.findByCriteria(criteria, begin, pageSize);
        return new Page<>(count, page, pageSize, entries);
    }
}
